<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/8/27
 * Time: 9:44 AM
 */
namespace app\common\services\content;

use app\common\models\Article;

class ArticleService
{

    public function getLastList($num,$hasCat=0,$titleLen=0,$descLen=0){
        \Log::debug('ArticleService getLastList');
        $query = Article::site()->select(['id','cid','title','description','publish_time','thumb']);
        if($hasCat){
            $query = $query
                ->with(['category' => function($query) {
                    return $query->select('id','name');
                }]);
        }
        $list = $query
            ->where('is_publish',Article::STATUS_YES)
            ->orderBy('id', 'desc')
            ->take($num)
            ->get();
        $list->map(function ($v) use ($hasCat,$titleLen,$descLen){
            if($titleLen){
                $v->title_str = mb_substr($v->title,0,$titleLen).'...';
            }
            if($descLen){
                $v->description_str = mb_substr($v->description,0,$descLen).'...';
            }
            $v->cname = '';
            if($hasCat){
                if($v['category']&&$v['category']['name']){
                    $v->cname = $v['category']['name'];
                }
            }
            $v->publish_time_fmt = date('Y-m-d H:i:s',$v->publish_time);
        });
        return $list;
    }

    public function getLevelList($params){
        $query = Article::site()->select('id','pid','title','links');
        if($params['pid']){
            $query->where('pid',$params['pid']);
        }
        if($params['cid']){
            $query->where('cid',$params['cid']);
        }
        $list = $query
            ->get();
        $res = [];
        foreach ($list as $v){
            if(!$v['pid']){
                $v['ptitle'] = '';
                array_push($res,$v);
            }
        }
        foreach ($res as $k => $v) {
            $res[$k]['subs'] = self::getSubs($list, $v['id'],$v['title']);
        }
        return $res;
    }

    public static function getSubs(&$list,$pid,$ptitle){
        $res = [];
        foreach ($list as $k => $v) {
            if ($v['pid'] == $pid) {
                unset($list[$k]);
                $v['ptitle'] = $ptitle;
                $v['subs'] = static::getSubs($list, $v['id'],$v['title']);
                if (empty($v['subs'])) {
                    unset($v['subs']);
                }
                $res[] = $v;
            }
        }
        return $res;
    }

}